package com.hspedu.homework.CorrectHomework01;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author DL5O
 * @version 1.0
 */
public class Client {
    public static void main(String[] args) throws IOException {
        String charset = "utf-8";
        String hostAddress= InetAddress.getLocalHost().getHostAddress();
        Socket socket = new Socket(hostAddress, 9999);//通过域名主机名 和端口号连接到主机
        boolean loop = true;
        while(loop) {
            //往服务端发送数据
            OutputStream outputStream = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream, charset));
            Scanner sc = new Scanner(System.in);
            System.out.print("请输入你的问题:");
            String question = sc.next();

            bw.write(question);//如果使用过的字符流，需要手动刷新，否则数据进去不去
            bw.newLine();//插入一个换行符，表示写入的内容结束，要求对方使用readLine();
            bw.flush();

            //接受从服务端发来的消息
            InputStream inputStream = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charset));
            String data = br.readLine();
            System.out.println(data);

            if(data.equals("quit")){
                loop = false;
                br.close();
                bw.close();
                socket.close();
            }
        }

        System.out.println("客戶端退出...");
    }
}
